package pdm.yamba.adapter;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import pdm.yamba.R;
import pdm.yamba.dto.*;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class StatusTimelineAdapter extends ArrayAdapter<Status> {

	private int resourceId;	
	private final Context context;
	SharedPreferences preferences;
	public StatusTimelineAdapter(Context context, int resourceId, List<Status> items) 
	{		
		super(context, resourceId, items);
        this.resourceId = resourceId;
        this.context = context;
        preferences = PreferenceManager.getDefaultSharedPreferences(context);        
	}
	
    @Override
    public View getView(int position, View convertView, ViewGroup parent) 
    {
    	// Item layout
    	RelativeLayout itemView;
    	
    	// Get the current item object
    	Status item = getItem(position);

        // Inflate the view (populate the layout)
        if(convertView == null)
        {
            itemView = new RelativeLayout(getContext());
            
            String inflater = Context.LAYOUT_INFLATER_SERVICE;
            
            LayoutInflater vi;
            vi = (LayoutInflater)getContext().getSystemService(inflater);
            vi.inflate(resourceId, itemView, true);
        }
        else
        {
        	itemView = (RelativeLayout) convertView;
        }        
        
        // Get the text boxes from the layout (timeline_item.xml) 
        // and assign the values from the object (TimelineItem)
        int messageLength = Integer.valueOf(preferences.getString("timelineLength", "70"));
        TextView statusText = (TextView)itemView.findViewById(R.id.statusText);
        String message = item.getMessage();       
        
        if(messageLength < message.length()) 
        {
        	message = message.substring(0, messageLength) + "...";
        }
        
        statusText.setText(message);
        
        TextView authorText =(TextView)itemView.findViewById(R.id.authorText);
        authorText.setText(item.getAuthor());        
        
        SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss", Locale.getDefault());
        String elapsedTime = dateFormat.format(new Date(item.getElapsedTime()));
        TextView elapsedTimeText =(TextView)itemView.findViewById(R.id.elapsedTimeText);
        elapsedTimeText.setText(elapsedTime);

        return itemView;    	
    }
}
